<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :rules="rules" :model="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="submitFn">确定</el-button>
        <el-button size="small" @click="cancelFn">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartmentAPI, getDeptsDetailAPI, updataDeptsAPI } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    parentId: {
      type: [Number, String],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList.map(item => item.code)
      // 判断是否是编辑状态
      // 当点击编辑时，已经将编辑项的id传递给了子组件：parentID
      // 如果传入的parentID和已有的数据中的某一个ID一致，排除当前项即可
      if (this.isEdit) {
        // filter方法筛选出id和parentid不一样的
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error(`部门编码${value}已存在`)) : callback()
    }
    const validName = (rule, value, callback) => {
      // 先找到同级item.id===parentId
      // 把同级部门的name组成一个新的数组，方便对比
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      // 判断是否编辑状态，找兄弟节点，对比
      if (this.isEdit) {
        // 先获取到本身
        const obj = this.originList.find(item => item.id === this.parentId)
        // 获取到本身的后获取其中的pid
        const pid = obj.pid
        // 根据pid获取同级，获取同级的同时需要将本身排除
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error(`部门名称${value}重复`)) : callback()
    }
    return {
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employees: []
    }
  },
  created() {
    this.getEmployeeSimpleFn()
    this.getDeptsDetail()
  },
  methods: {
    // 数据回填
    async getDeptsDetail() {
      if (this.isEdit) {
        // 调取接口，传入当前父组件传回的id，获取此id的相关数据
        const res = await getDeptsDetailAPI(this.parentId)
        // 传回的数据放入form中进行数据回填
        this.form = res.data
      }
    },
    // 新增组织架构方法
    async addDeptsFn() {
      // 调用接口，将需要提交的参数打散组成新的对象提交给body
      const res = await addDepartmentAPI({ ...this.form, pid: this.parentId })
      // console.log(res)
      // 给用户返回提示信息
      this.$message.success(res.message)
      // 子传父，在父级绑定自定义事件，从而操作弹出层
      this.$emit('updata-list')
    },
    // 编辑组织架构方法
    async editDeptsFn() {
      // 调用接口，将编辑后的表单数据重新提交
      const res = await updataDeptsAPI(this.form)
      // console.log(res)
      // 给用户返回提示信息
      this.$message.success(res.message)
      // 子传父，在父级绑定自定义事件，从而操作弹出层
      this.$emit('updata-list')
    },
    // 表单提交
    submitFn() {
      this.$refs.form.validata(valid => {
        if (!valid) return
        this.isEdit ? this.editDeptsFn() : this.addDeptsFn()
      })
    },
    cancelFn() {
      this.$emit('close')
    },
    async getEmployeeSimpleFn() {
      const res = await getEmployeeSimple()
      this.employees = res.data
    }
  }
}
</script>

<style lang="scss" scoped></style>

